import {config} from "../config"
import {store} from "store"
class Request {
    constructor(baseURL) {
      this.baseURL = baseURL || '';
    }
  
    request(url, method, data = {}) {
      return new Promise((resolve, reject) => {
        let token = store.get("token")
        let header = {
          'Content-Type': 'application/json' // 设置请求头为 application/json
        }
        if(token) {
          header.token = token
        }
        wx.request({
          url: this.baseURL + url,
          method: method,
          data: data,
          header: header,
          success: (res) => {
            let token = res.header["token"]
            if(token) {
              store.put("token",token)
            }
            if (res.statusCode === 200) {
              resolve(res.data);
            } else {
              // 处理非 200 的错误状态
              reject({
                error: 'Request failed',
                statusCode: res.statusCode,
                data: res.data
              });
            }
          },
          fail: (err) => {
            reject({
              error: 'Network error',
              detail: err
            });
          }
        });
      });
    }
  
    // GET 请求方法
    get(url, data) {
      return this.request(url, 'GET', data);
    }
  
    // POST 请求方法
    post(url, data) {
      return this.request(url, 'POST', data);
    }
  
    // PUT 请求方法
    put(url, data) {
      return this.request(url, 'PUT', data);
    }
  
    // DELETE 请求方法
    delete(url, data) {
      return this.request(url, 'DELETE', data);
    }

    // Try
    try(url, data) {
        console.log(url, data)
    }
  }
  
  // 导出实例
export default new Request(config.host + config.api_prefix)